package com.example.demo1.controller;

import com.example.demo1.domain.Picture;
import com.example.demo1.entity.Updown;
import com.example.demo1.repository.PictureDao;
import com.example.demo1.utils.AliOSSUtils;
import com.example.demo1.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


@Slf4j
@RestController
@RequestMapping("/detect")
public class SaveController {
    @Autowired
    public AliOSSUtils aliOSSUtils;

    @Autowired
    public PictureDao pictureDao;
    //保存实验信息，存储到数据库
    @PostMapping("/uplode")
    public Result Updownimage( Updown updown) {
        MultipartFile file = updown.getImage();
        log.info("文件上传：{}", file);
        //检查图片是否为空
        if (file == null) {
            return Result.error("1", "文件为空");
        }
        try {
            Picture picture=new Picture();
            String suffix;
            String filePath = aliOSSUtils.upload(file);
            String picture_name;
            if (updown.getName() == null || updown.getName().isEmpty()) {

                Date date = new Date();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if ("meanwhile".equals(updown.getChoice())) {
                    suffix = "同时间对比图";
                } else if ("change".equals(updown.getChoice())) {
                    suffix = "变化趋势图";
                } else {
                    return Result.error("1", "请选择检测模式");
                }
                picture_name = dateFormat.format(date) + suffix;
            } else {
                picture_name = updown.getName();
            }
            picture.setPicture(filePath);
            picture.setUsername(updown.getUsername());
            picture.setExperiment_name(updown.getExperment_name());
            picture.setTeam_name(updown.getTeam_name());
            picture.setPicture_name(picture_name);
            pictureDao.save(picture);
            return Result.success("图片保存成功");

        } catch (IOException e) {
            log.error("文件上传失败：", e);
            return Result.error("1", "图片保存失败");
        }
    }
}



